// jsmud: JavaScript MUD Kernel
// Copyright (C) 2005,2008 Mojodo, Inc.
// All rights reserved.
// See COPYING for licensing details.

function checkPass(user,pass) {
	var result = DB.queryRow('SELECT name FROM account WHERE name=?001 AND pass=?002', user, pass);
	return result ? true : false;
}

function onConnect(player) {
	// send greeting
	var greeting = File.get('greeting.txt');
	player.send(greeting);

	player.send('(Username is "admin", password is "password")\n');
	player.send('Username: ');
	player.mode = 0;

	player.shutdown = function() {
		this.disconnect();
	}
	player.onInput = function(text) {
		if (this.mode == 0) {
			this.uname = text;
			this.mode = 1;
			this.send('Password: ');
			this.setEcho(false);
		} else if (this.mode == 1) {
			this.setEcho(true);
			var check = checkPass(this.uname, text);
			delete this.uname;
			if (!check)
				this.send('\nFAIL\n');
			else
				this.send('\nOK\n');
			this.send('Command: ');
			this.mode = 2;
		} else {
			this.send('You said: ' + text + '\n');
			if (text == 'look') {
				this.send('Database:\n');
				var result = querySql('SELECT first,second FROM test');
				while (obj = result.next())
					this.send('Record: ' + obj.first + ',' + obj.second + '\n');
			} else if (text == 'quit') {
				this.shutdown();
			} else if (text == 'help') {
				this.send('Help:\n');
				this.send(' look   - show database test\n');
				this.send(' quit   - disconnect\n');
			}
		}
	}
	player.onHangup = function() {
	}
}

function initialize() {
	Net.listen(getSetting('interface', '0.0.0.0'), 4545, onConnect);
}
